// BluetoothManager.h
#pragma once
#include "ConfigManager.h"
#include "HardwareConfig.h"

#if BLE_SUPPORTED
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// BLE UUID定义
#define SERVICE_UUID        "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#endif

#if CLASSIC_BT_SUPPORTED
#include <BluetoothSerial.h>
#endif
 
class BluetoothManager {
private:
    ConfigManager& config;
    bool btStarted;
    bool isClassicMode;
    
#if CLASSIC_BT_SUPPORTED
    BluetoothSerial* serialBT;
#endif

#if BLE_SUPPORTED
    BLEServer* pServer;
    BLEService* pService;
    BLECharacteristic* pTxCharacteristic;
    BLECharacteristic* pRxCharacteristic;
    bool deviceConnected;
    bool oldDeviceConnected;
#endif

    void setupBLE(const char* deviceName);
    void setupClassicBT(const char* deviceName);
    
public:
    BluetoothManager(ConfigManager& cfg);
    ~BluetoothManager();
    
    bool begin();
    void update();
    bool startClassicBT(const char* deviceName);
    bool startBLE(const char* deviceName);
    void stopBT();
    String getStatus();
    bool isConnected();
    
    // BLE 回调类
#if BLE_SUPPORTED
    class MyServerCallbacks : public BLEServerCallbacks {
    private:
        BluetoothManager* manager;
    public:
        MyServerCallbacks(BluetoothManager* mgr) : manager(mgr) {}
        void onConnect(BLEServer* pServer) override;
        void onDisconnect(BLEServer* pServer) override;
    };
    
    class RxCallbacks : public BLECharacteristicCallbacks {
    private:
        BluetoothManager* manager;
    public:
        RxCallbacks(BluetoothManager* mgr) : manager(mgr) {}
        void onWrite(BLECharacteristic* pCharacteristic) override;
    };
#endif
};